<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas id="myCanvas" width="500" height="500"></canvas>
    <script>
      let selectedRect = null; // 用于存储被选中的矩形
      const canvas = document.getElementById("myCanvas");
      const ctx = canvas.getContext("2d");
      let offsetX = 0,
      offsetY = 0;
      function drawRectangles() {
        ctx.fillStyle = "blue";
        ctx.fillRect(50, 50, 100, 100); // 绘制一个矩形
      }
      function isPointInRect(x, y, rect) {
        return (
          x > rect.x &&
          x < rect.x + rect.width &&
          y > rect.y &&
          y < rect.y + rect.height
        );
      }

      function handleMouseDown(event) {
        const rects = [{ x: 50, y: 50, width: 100, height: 100 }]; // 矩形数组
        const rect = rects.find((r) =>
          isPointInRect(event.offsetX, event.offsetY, r)
        );
        if (rect) {
          selectedRect = rect;
        } else {
          selectedRect = null;
        }
      }
     

      function handleMouseMove(event) {
        if (selectedRect) {
          selectedRect.x = event.offsetX - offsetX;
          selectedRect.y = event.offsetY - offsetY;
          draw(); // 重绘Canvas以显示移动后的矩形
        }
      }

      function handleMouseUp() {
        selectedRect = null; // 释放选中的矩形，停止拖拽
      }
      function draw(c) {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // 清空Canvas
        drawRectangles(); // 重新绘制所有矩形，包括移动后的矩形
      }

      function init() {
      
        
        canvas.addEventListener("mousedown", handleMouseDown);
        canvas.addEventListener("mousemove", handleMouseMove);
        canvas.addEventListener("mouseup", handleMouseUp);
        canvas.addEventListener("mouseout", handleMouseUp); // 当鼠标离开Canvas时也停止拖拽
        draw(); // 初始绘制
      }

      init(); // 初始化函数调用
    </script>
  </body>
</html>
